<script setup>
import { ref, onMounted, onUnmounted, computed, nextTick } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import TabBar from '@/components/TabBar.vue'
import { wsManager } from '@/utils/websocket'
import { useNotificationStore } from '@/stores/notification'

const route = useRoute()
const currentTime = ref('')
const notificationStore = useNotificationStore()

// WebSocket 消息监听器
let unsubscribeWs = null

// 判断是否显示TabBar
const showTabBar = computed(() => {
  const result = route.matched.some(record => record.meta?.showTabBar === true)
  console.log('[TabBar Debug]', {
    path: route.path,
    matched: route.matched.map(r => ({ path: r.path, meta: r.meta })),
    showTabBar: result
  })
  return result
})

const updateTime = () => {
  const now = new Date()
  const hours = String(now.getHours()).padStart(2, '0')
  const minutes = String(now.getMinutes()).padStart(2, '0')
  currentTime.value = `${hours}:${minutes}`
}

let timer = null

// 自定义通知弹窗状态
const showNotificationPopup = ref(false)
const notificationData = ref({
  title: '',
  content: '',
  type: 'info'
})

// 显示自定义通知弹窗
const showCustomNotification = (title, content, type = 'info') => {
  notificationData.value = { title, content, type }
  showNotificationPopup.value = true
  
  // 3秒后自动关闭
  setTimeout(() => {
    showNotificationPopup.value = false
  }, 3000)
}

// 关闭通知弹窗
const closeNotificationPopup = () => {
  showNotificationPopup.value = false
}

// 点击通知跳转到通知页面
const goToNotificationPage = () => {
  showNotificationPopup.value = false
  if (route.path !== '/notification') {
    window.location.href = '/#/notification'
  }
}

// WebSocket 消息处理函数
const handleWebSocketMessage = (data) => {
  console.log('[App] 📨 收到 WebSocket 消息:', data)
  
  // 跳过连接状态消息
  if (data.type === 'connected' || data.type === 'disconnected' || data.type === 'heartbeat') {
    return
  }
  
  // 处理系统通知消息
  if (data.type && data.title && data.content) {
    // 增加未读数
    notificationStore.incrementUnread()
    
    // 显示自定义通知弹窗
    showCustomNotification(data.title, data.content, data.type)
    return
  }
  
  // 兼容其他格式的消息
  if (data.code === 200 && data.msg && data.msg.includes('认证')) {
    notificationStore.incrementUnread()
    
    const userName = data.data?.name || '用户'
    showCustomNotification('实名认证成功', `恭喜${userName}，您的实名认证已通过审核！`, 'success')
  }
}

// 获取通知类型
const getNotificationType = (type) => {
  const typeMap = {
    'system': 'info',
    'success': 'success',
    'warning': 'warning',
    'error': 'error'
  }
  return typeMap[type] || 'info'
}

onMounted(() => {
  updateTime()
  timer = setInterval(updateTime, 1000)
  
  // 初始化全局 WebSocket 连接
  const userToken = localStorage.getItem('token')
  const storedUserInfo = localStorage.getItem('userInfo')
  if (userToken && storedUserInfo) {
    try {
      const userInfoData = JSON.parse(storedUserInfo)
      const userId = userInfoData.id
      if (userId) {
        console.log('[App] 初始化全局 WebSocket，userId:', userId)
        wsManager.init(userId)
        
        // 注册全局消息监听器
        unsubscribeWs = wsManager.onMessage(handleWebSocketMessage)
        console.log('[App] ✅ 全局 WebSocket 消息监听已注册')
      }
    } catch (error) {
      console.error('[App] 初始化 WebSocket 失败:', error)
    }
  }
})

onUnmounted(() => {
  if (timer) {
    clearInterval(timer)
  }
  
  // 清理 WebSocket 监听器
  if (unsubscribeWs) {
    unsubscribeWs()
    console.log('[App] 清理全局 WebSocket 监听器')
  }
})

// 画布模式控制
const isCanvasMode = ref(true)

const toggleCanvasMode = () => {
  isCanvasMode.value = !isCanvasMode.value
}

// 画布滚动容器引用与滚动指示
const canvasRef = ref(null)
const isScrolling = ref(false)
let scrollTimer = null

const handleScroll = () => {
  isScrolling.value = true
  if (scrollTimer) clearTimeout(scrollTimer)
  scrollTimer = setTimeout(() => {
    isScrolling.value = false
  }, 600)
}

// 图片预览（点击画布内图片查看原图）
const previewUrl = ref('')
const closePreview = () => { previewUrl.value = '' }
const handleCanvasClick = (e) => {
  const target = e.target
  if (target && target.tagName === 'IMG') {
    const src = target.getAttribute('src')
    if (src) previewUrl.value = src
  }
}

// 尺寸校验方法（控制台与全局方法）
const logCanvasSize = () => {
  const el = iphoneContainerRef.value
  if (!el) return
  const rect = el.getBoundingClientRect()
  // 控制台输出实际尺寸
  // 为便于调试，保持稳定结构输出
  console.log('[CanvasSize]', { width: rect.width, height: rect.height })
}

const iphoneContainerRef = ref(null)

onMounted(async () => {
  await nextTick()
  if (canvasRef.value) {
    canvasRef.value.addEventListener('scroll', handleScroll, { passive: true })
    canvasRef.value.addEventListener('click', handleCanvasClick)
  }
  // 暴露全局校验方法
  window.__checkCanvasSize = logCanvasSize
  logCanvasSize()
})

onUnmounted(() => {
  if (scrollTimer) clearTimeout(scrollTimer)
  if (canvasRef.value) {
    canvasRef.value.removeEventListener('scroll', handleScroll)
    canvasRef.value.removeEventListener('click', handleCanvasClick)
  }
})
</script>

<template>
  <!-- 画布模式切换按钮 -->
  <button class="mode-toggle-btn" @click="toggleCanvasMode" :title="isCanvasMode ? '切换到原始模式' : '切换到画布模式'">
    <svg v-if="isCanvasMode" viewBox="0 0 24 24" width="20" height="20" fill="currentColor">
      <path d="M19 4H5c-1.11 0-2 .9-2 2v12c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm0 14H5V8h14v10z"/>
    </svg>
    <svg v-else viewBox="0 0 24 24" width="20" height="20" fill="currentColor">
      <path d="M17 1.01L7 1c-1.1 0-2 .9-2 2v18c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2V3c0-1.1-.9-1.99-2-1.99zM17 19H7V5h10v14z"/>
    </svg>
  </button>

  <!-- 原始模式：全屏显示 -->
  <div v-if="!isCanvasMode" class="original-mode">
    <router-view></router-view>
    <TabBar v-if="showTabBar" />
  </div>

  <!-- 画布模式：iPhone 16 Pro Max 容器 -->
  <div v-else class="canvas-mode-wrapper">
    <div ref="iphoneContainerRef" class="iphone-container">
      <!-- 画布内容区域 -->
      <div ref="canvasRef" class="iphone-canvas" :class="{ 'is-scrolling': isScrolling }">
        <router-view></router-view>
      </div>
      
      <!-- TabBar 放在画布外，这样不会随内容滚动 -->
      <TabBar v-if="showTabBar" class="canvas-tabbar" />
      
      <!-- 自定义通知弹窗 -->
      <transition name="notification-fade">
        <div v-if="showNotificationPopup" class="custom-notification" @click="goToNotificationPage">
          <div class="notification-header">
            <div class="notification-icon" :class="`notification-${notificationData.type}`">
              <svg v-if="notificationData.type === 'success'" viewBox="0 0 24 24" width="20" height="20" fill="currentColor">
                <path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41L9 16.17z"/>
              </svg>
              <svg v-else-if="notificationData.type === 'warning'" viewBox="0 0 24 24" width="20" height="20" fill="currentColor">
                <path d="M1 21h22L12 2 1 21zm12-3h-2v-2h2v2zm0-4h-2v-4h2v4z"/>
              </svg>
              <svg v-else-if="notificationData.type === 'error'" viewBox="0 0 24 24" width="20" height="20" fill="currentColor">
                <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-2h2v2zm0-4h-2V7h2v6z"/>
              </svg>
              <svg v-else viewBox="0 0 24 24" width="20" height="20" fill="currentColor">
                <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-2h2v2zm0-4h-2V7h2v6z"/>
              </svg>
            </div>
            <button class="notification-close" @click.stop="closeNotificationPopup">
              <svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor">
                <path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12 19 6.41z"/>
              </svg>
            </button>
          </div>
          <div class="notification-content">
            <div class="notification-title">{{ notificationData.title }}</div>
            <div class="notification-message">{{ notificationData.content }}</div>
          </div>
        </div>
      </transition>
      
      <!-- 图片预览层 -->
      <div v-if="previewUrl" class="image-preview" @click="closePreview">
        <img :src="previewUrl" alt="preview" />
      </div>
    </div>
  </div>
</template>

<style scoped>
/* ==================== 模式切换按钮 ==================== */
.mode-toggle-btn {
  position: fixed;
  top: 20px;
  right: 20px;
  z-index: 10000;
  width: 48px;
  height: 48px;
  border-radius: 50%;
  background: #ffffff;
  border: 1px solid #e0e0e0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  color: #333;
}

.mode-toggle-btn:hover {
  background: #f0f0f0;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
  transform: scale(1.05);
}

.mode-toggle-btn:active {
  transform: scale(0.95);
}

/* ==================== 原始模式 ==================== */
.original-mode {
  width: 100%;
  min-height: 100vh;
  overflow: visible;
}

/* ==================== 画布模式外层容器 ==================== */
.canvas-mode-wrapper {
  /* 渐变灰背景，增强沉浸感 */
  background: linear-gradient(180deg, #f0f0f2 0%, #e0e0e5 100%);
  
  /* 固定铺满视口，容器自身不滚动 */
  position: fixed;
  inset: 0;
  width: 100vw;
  height: 100vh;
  overflow: hidden;

  /* 居中画布 */
  display: flex;
  align-items: center;
  justify-content: center;
  box-sizing: border-box;
}

/* ==================== iPhone 16 Pro Max 容器 ==================== */
.iphone-container {
  /* 精准尺寸：严格匹配 iPhone 16 Pro Max */
  width: 428px;
  height: 926px;

  /* 禁止缩放和拉伸 */
  flex-shrink: 0;

  /* 1px 浅灰边框，内背景纯白 */
  border: 1px solid #e5e5e7;
  background: #ffffff;

  /* 轻微圆角 */
  border-radius: 14px;

  /* 轻量、真实的悬浮阴影 */
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);

  /* 相对定位，便于子元素绝对定位 */
  position: relative;

  /* 防止内容溢出 */
  overflow: hidden;
}

/* ==================== 尺寸标识 ==================== */
.size-label {
  position: absolute;
  top: 8px;
  right: 8px;
  z-index: 9999;
  background: rgba(255, 255, 255, 0.9);
  color: #666;
  font-size: 12px;
  font-weight: 500;
  padding: 4px 8px;
  border-radius: 10px;
  border: 1px solid #e5e5e7;
  cursor: pointer;
  font-family: 'SF Mono', Monaco, 'Cascadia Code', 'Courier New', monospace;
  letter-spacing: 0.3px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.06);
}

/* ==================== 画布内容区域 ==================== */
.iphone-canvas {
  /* 填充整个容器 */
  width: 100%;
  height: 100%;

  /* 仅内容区域滚动 */
  overflow-y: auto;
  overflow-x: hidden;
  overscroll-behavior: contain;
  -webkit-overflow-scrolling: touch;
  touch-action: pan-y;

  /* 相对定位 */
  position: relative;

  /* 背景色 */
  background: #ffffff;

  /* 文本与表格适配 */
  word-break: break-word;
  overflow-wrap: anywhere;
}

/* 滚动条：默认隐藏，滚动时显示 2px 半透明指示 */
.iphone-canvas::-webkit-scrollbar { width: 0; height: 0; }
.iphone-canvas.is-scrolling::-webkit-scrollbar { width: 2px; }
.iphone-canvas.is-scrolling::-webkit-scrollbar-thumb { background: rgba(0, 0, 0, 0.2); border-radius: 2px; }
.iphone-canvas.is-scrolling::-webkit-scrollbar-track { background: transparent; }

/* Firefox */
.iphone-canvas { scrollbar-width: none; }
.iphone-canvas.is-scrolling { scrollbar-width: thin; scrollbar-color: rgba(0,0,0,0.2) transparent; }

/* 表格类内容优先压缩列宽，避免横向滚动 */
.iphone-canvas :deep(table) { table-layout: fixed; width: 100%; }
.iphone-canvas :deep(th),
.iphone-canvas :deep(td) { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }

/* 图片自适应画布宽度，点击可预览原图 */
.iphone-canvas :deep(img) { max-width: 100%; height: auto; display: block; cursor: zoom-in; }

/* 在画布模式下，TabBar 相对于 .iphone-container 固定定位，不随内容滚动 */
.iphone-container {
  position: relative; /* 为 absolute 定位的 TabBar 提供参考 */
}

.canvas-tabbar {
  position: absolute !important;
  left: 0 !important;
  right: 0 !important;
  bottom: 0 !important;
  height: 60px !important;
  border-radius: 0 0 20px 20px !important; /* 匹配 iPhone 容器的圆角 */
  z-index: 1000 !important;
}

/* 原始模式下，TabBar 使用 fixed 定位 */
.original-mode .tabbar {
  position: fixed !important;
}

/* 预留底部安全区，避免内容被 TabBar 遮挡 */
.iphone-canvas :deep(.page-container),
.iphone-canvas :deep(.home-container) { 
  padding-bottom: 60px; 
}

/* 顶部状态栏（若有）固定 44px 高度 */
.iphone-canvas :deep(.status-bar) { height: 44px; line-height: 44px; }

/* 按钮与输入的 iOS 风格点击反馈光晕（8px） */
.iphone-canvas :deep(button),
.iphone-canvas :deep(.el-button),
.iphone-canvas :deep(input),
.iphone-canvas :deep(textarea),
.iphone-canvas :deep(.el-input__inner) {
  transition: box-shadow 0.2s ease, transform 0.05s ease;
}
.iphone-canvas :deep(button:active),
.iphone-canvas :deep(.el-button:active),
.iphone-canvas :deep(input:focus),
.iphone-canvas :deep(textarea:focus),
.iphone-canvas :deep(.el-input__inner:focus) {
  box-shadow: 0 0 0 8px rgba(22, 119, 255, 0.1);
}

/* ==================== 自定义通知弹窗 ==================== */
.custom-notification {
  position: absolute;
  top: 16px;
  left: 16px;
  right: 16px;
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  z-index: 9999;
  cursor: pointer;
  overflow: hidden;
  animation: slideDown 0.3s ease;
}

@keyframes slideDown {
  from {
    transform: translateY(-100%);
    opacity: 0;
  }
  to {
    transform: translateY(0);
    opacity: 1;
  }
}

.notification-fade-enter-active,
.notification-fade-leave-active {
  transition: all 0.3s ease;
}

.notification-fade-enter-from {
  transform: translateY(-100%);
  opacity: 0;
}

.notification-fade-leave-to {
  transform: translateY(-100%);
  opacity: 0;
}

.notification-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px 8px;
}

.notification-icon {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.notification-success {
  background: #f0f9ff;
  color: #67c23a;
}

.notification-warning {
  background: #fef0f0;
  color: #e6a23c;
}

.notification-error {
  background: #fef0f0;
  color: #f56c6c;
}

.notification-info {
  background: #f4f4f5;
  color: #909399;
}

.notification-close {
  width: 24px;
  height: 24px;
  border: none;
  background: transparent;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
  border-radius: 50%;
  transition: all 0.2s;
  padding: 0;
}

.notification-close:hover {
  background: #f4f4f5;
  color: #606266;
}

.notification-content {
  padding: 0 16px 12px;
}

.notification-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.notification-message {
  font-size: 14px;
  color: #606266;
  line-height: 1.5;
}

/* 图片预览层样式（居中显示，点击关闭） */
.image-preview {
  position: absolute;
  inset: 0;
  background: rgba(0,0,0,0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10000;
}
.image-preview img { max-width: 100%; max-height: 100%; object-fit: contain; }

/* ==================== 响应式适配 ==================== */
/* 当视口宽度小于画布+边距时，确保画布完整显示（通过外层滚动） */
@media (max-width: 468px) {
  .mode-toggle-btn {
    top: 10px;
    right: 10px;
    width: 40px;
    height: 40px;
  }
  .mode-toggle-btn svg { width: 18px; height: 18px; }
}

/* 平板和小屏设备：保持画布比例不变，通过滚动查看 */
@media (max-height: 1006px) {
  .canvas-mode-wrapper { align-items: center; }
}
</style>
